﻿using Company.Core;
using Company.Core.Helpers;
using Company.Hardware.Base;
using Company.Hardware.Base.Entities;
using Company.Hardware.Base.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Company.Hardware.YaHuiLong
{
    class IFlash3000Decoder : IDecoder
    {
        public event Action<string>? OnNotify;
        public event Action<HL7>? OnUpload;

        private readonly SerialPortService serialPortService = new();
        private readonly TcpService tcpService = new() ;
        private Config? Config;

        public async Task<bool> InitAsync(Config config)
        {
            Config = config;
            string info = $"{this.GetType().FullName}";
            OnNotify?.Invoke("正在加载"+info);
            ProtocolType protocolType = (ProtocolType)config.Protocol;
            switch (protocolType)
            {
                case ProtocolType.SerialPort:
                    //串口方式
                    info += $"{config.SerialName}-{config.BaudRate}";
                    serialPortService.ConnectionAsync(config);
                    if (serialPortService.Connected)
                    {
                        Logs.Info(info+"初始化连接成功");
                        OnNotify?.Invoke(info + "初始化连接成功");
                    }
                    else
                    {
                        Logs.Info(info + "初始化连接失败");
                        OnNotify?.Invoke(info + "初始化连接失败");
                        return false;
                    }
                    break;
                    
                case ProtocolType.TcpClient:
                    //TCP的客户端模式
                    info += $"{config.IpAddress}-{config.Port}";
                    await tcpService.ConnectionTcpClientAsync(config);
                    if (tcpService.Connected)
                    {
                        Logs.Info(info + "初始化连接成功");
                        OnNotify?.Invoke(info + "初始化连接成功");
                    }
                    else
                    {
                        Logs.Info(info + "初始化连接失败");
                        OnNotify?.Invoke(info + "初始化连接失败");
                        return false;
                    }
                    break;
                case ProtocolType.TcpServer:
                    //TCP服务器端模式
                    info += $"{config.IpAddress}-{config.Port}";
                    await tcpService.ConnectionTcpServerAsync(config);
                    if (tcpService.Connected)
                    {
                        Logs.Info(info + "初始化连接成功");
                        OnNotify?.Invoke(info + "初始化连接成功");
                    }
                    else
                    {
                        Logs.Info(info + "初始化连接失败");
                        OnNotify?.Invoke(info + "初始化连接失败");
                        return false;
                    }
                    break;
                default:
                    break;
            }
            return true;
        }

        public bool Stop()
        {
            throw new NotImplementedException();
        }

        public Task<bool> StartAsync(IUploader uploader)
        {
            return Task.Run<bool>(() =>
            {
                ProtocolType protocolType = (ProtocolType)Config.Protocol;
                switch (protocolType)
                {
                    case ProtocolType.SerialPort:
                        if(!serialPortService.Connected)
                        {
                            return false;
                        }
                        serialPortService.OnReceived += OnReceived;
                        
                        break;
                    case ProtocolType.TcpClient:
                    case ProtocolType.TcpServer:
                        if (!tcpService.Connected)
                        {
                            return false;
                        }
                        tcpService.OnReceived += OnReceived;
                        return tcpService.Start();
                        break;
                    default:
                        break;
                }
                return false;
            });
        }

        private string orginalString = string.Empty;//源数据

        /// <summary>
        /// 医疗设备回传的数据
        /// </summary>
        /// <param name="data"></param>
        private void OnReceived(string data)
        {
            //先判断数据是否接收完整
            //接收到的数据如果是一条数据的开始字符，就先清空
            if (data[0] == '\v')
            {
                orginalString = string.Empty;
            }

            if (string.IsNullOrEmpty(orginalString))
            {
                orginalString = data;
            }
            else
            {
                orginalString += data;
            }

            if (orginalString.Length >= 2)
            {
                if (orginalString[0]=='\v'&& !(orginalString[orginalString.Length - 2] == '\u001c' && orginalString[orginalString.Length - 1] == '\r'))
                {
                    return;
                }
            }
            else
            {
                return;
            }

            //表示接收到完整的数据
            OnNotify?.Invoke(orginalString);

            //开始解码和上传
            HL7 entity = DecoderHelper.DecodeHL7(orginalString);

            //解码完成后清空源码
            orginalString = string.Empty;

            //要求上传该数据包
            OnUpload?.Invoke(entity);
        }

        
    }
}
